﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using LDataAccess;
using LModels.Base;
using Proxy = LModels.Proxy.Proxy;

namespace Models
{
    public class Factory<T> where T : BaseModel
    {

        protected ProxyClass px;
       
        public Factory(ProxyClass proxy)
        {
            px = proxy;
        }

        public BaseModel Load(long key)
        {
            BaseModel Instance = (T)Activator.CreateInstance(typeof(T), new object[] { px });
            return Instance.Load(key);
        }

        public BaseModel New()
        {
            return (T)Activator.CreateInstance(typeof(T), new object[] { px });
        }
    }


    public class FactoryCollection<T> where T : BaseCollection
    {

        protected ProxyClass px;
        private T Instance;

        public T GetInstance()
        {
            return Instance ?? (Instance = (T) Activator.CreateInstance(typeof (T), new object[] {px}));
        }

        public FactoryCollection(ProxyClass proxy)
        {
            px = proxy;
            
        }

        public BaseCollection New()
        {
            return (T) Activator.CreateInstance(typeof (T), new object[] {px});
        }


        public T List(string methodName, object[] parameters)
        {
            Instance = (T) Activator.CreateInstance(typeof (T), new object[] {px});

            Type type = Type.GetType(typeof(T).FullName);

            MethodInfo method = type.GetMethod(methodName);
            return (T)method.Invoke(Instance, parameters);
        }
        
    }

}
